import request from 'request';
import { isString } from 'lodash';

/**
 * 默认路径转换方法
 * @param  {string} incomingPath
 * @return {string}
 */
function defaultMapFunction(incomingPath) {
    return incomingPath;
}

/**
 * 创建代理服务中间件
 * @return {Function}
 */
export default function createProxyMiddleware({
    host,
    map = defaultMapFunction
} = {}) {

    let requestHandler;

    if (isString(host)) {
        requestHandler = request.defaults({
            baseUrl: host
        });
    } else {
        throw new Error('"host" is required');
    }

    /**
     * 代理服务中间件
     * @return {Promise}
     */
    return async function proxyMiddleware(ctx, next) {
        const path = map(ctx.url);
        const agent = requestHandler({
            url: path,
            followRedirect: false
        });

        // Use incoming request
        ctx.req.pipe(agent);
        ctx.body = agent;
    };
}